package com.springboot.show_web.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义异步线程池配置
 * Created by yaosheng on 2019/12/1.
 */
@Slf4j
@Configuration
public class AsyncPoolConfig implements AsyncConfigurer {

    @Bean
    @Override
    public Executor getAsyncExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);            //线程池核心的数量，默认为1
        executor.setMaxPoolSize(20);             //线程池维护的核心数量
        executor.setQueueCapacity(20);           //缓冲队列任务的个数
        executor.setKeepAliveSeconds(60);        //超出核心线程池个数之外的线程最大存活时间，默认为60秒
        executor.setThreadNamePrefix("GreatAsync_");              //线程名的前缀
        executor.setWaitForTasksToCompleteOnShutdown(true);       //是否等待所有线程池执行完之后关闭，默认为false
        executor.setAwaitTerminationSeconds(60);                  //线程等待的时常，默认为0
        //拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    /**
     * 定义异步任务异常处理类
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler(){
        return null;
    }

    class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler{

        @Override
        public void handleUncaughtException(Throwable throwable, Method method,Object... objects){
            log.info("AsyncError: {},Method: {}",throwable.getMessage(),method.getName());
            throwable.printStackTrace();

            //TODO 发送邮件或者短信
        }
    }
}